#include "coin-button.h"

CoinButton::CoinButton(int x, int y, bool is_gold)
{
    this->x = x;

    this->y = y;

    this->is_gold = is_gold;

    this->is_animation = false;

    this->timer = new QTimer(this);

    this->gold_coin_image_pathname = GOLD_COIN;

    this->silver_coin_image_pathname = SILVER_COIN;

    this->general_coin_image_pathname = GENERAL_COIN;

    QString image_pathname;
    if (is_gold) {
        image_pathname = gold_coin_image_pathname;

    } else {
        image_pathname = silver_coin_image_pathname;
    }

    // 设置硬币图片
    setButtonImage(image_pathname);

    // 设置硬币反转的过程
    connect(this->timer, &QTimer::timeout, this, [=]() {
        if (!this->is_gold) { // 逻辑判断有点问题
            setButtonImage(this->general_coin_image_pathname.arg(start++));

            if (start > end) {
                timer->stop();
                this->is_gold = false;
                this->is_animation = false;
            }

        } else {
            setButtonImage(this->general_coin_image_pathname.arg(start--));

            if (start < end) {
                timer->stop();
                this->is_gold = true;
                this->is_animation = false;
            }
        }
    });
}

CoinButton::~CoinButton()
{

}


bool CoinButton::event(QEvent *event)
{
    // 其他事件交给父类处理
    return QWidget::event(event);
}

void CoinButton::mousePressEvent(QMouseEvent *event)
{
    // 当前硬币在翻转过程中或者硬币功能结束时, 拦截硬币的点击事件
    if (this->is_animation || this->is_finish) {
        return;
    }

    return QPushButton::mousePressEvent(event);
}

void CoinButton::mouseReleaseEvent(QMouseEvent *event)
{
    return QPushButton::mouseReleaseEvent(event);
}

void CoinButton::setButtonImage(QString image_pathname)
{
    QPixmap pixmap;
    bool result = pixmap.load(image_pathname);

    if(!result) {
        qDebug() << "加载图片 " << image_pathname << " 失败!";
        return;
    }

    // 设置图片缩放比
    pixmap = pixmap.scaled(pixmap.width() * 1, pixmap.height() * 1);

    // 设置图片固定大小
    this->setFixedSize(pixmap.size());

    // 设置不规则图片样式
    this->setStyleSheet("QPushButton{border:0px;}");

    // 设置图标
    this->setIcon(pixmap);

    // 设置图标大小
    this->setIconSize(pixmap.size());
}

void CoinButton::finish()
{
    this->is_finish = true;
}

bool CoinButton::getCoinState()
{
    return this->is_gold;
}

void CoinButton::flipCoin(int time)
{
    if (is_gold) { // 金币变成银币
        this->start = 1;
        this->end = 8;

    } else { // 银币变成金币
        this->start = 8;
        this->end = 1;
    }

    // 及时更改硬币的状态, 避免多次连续点击时出现状态异常的问题
    this->is_gold = !this->is_gold;

    // 当前银币按钮处于动画阶段
    this->is_animation = true;

    // 使用定时器实现硬币翻转的动画
    timer->start(time);
}
